package cn.school.mybatis.servlet;

import cn.school.mybatis.Util.SpringMButil;
import cn.school.mybatis.pojo.Grade;
import cn.school.mybatis.pojo.Result;
import cn.school.mybatis.pojo.Student;
import cn.school.mybatis.pojo.Subject;
import cn.school.mybatis.service.ResultService;
import cn.school.mybatis.service.StudentService;
import cn.school.mybatis.service.SubjectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//通配符的请求地址
@WebServlet("*.ex")
public class ExamResultMainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //显示成绩信息
    protected void exInfoServlet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int pageNo = 1;
        int pageSize = 10;

        try {
            pageNo = Integer.parseInt(request.getParameter("pageNo"));
        } catch (Exception e) {
            pageNo = 1;
        }
        try {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            pageSize = 10;
        }


        //条件查询
//        String sname = request.getParameter("sname");
//        String telephone = request.getParameter("telephone");
//        sname = sname == null ? "" : sname;
//        telephone = telephone == null ? "" : telephone;
        Map<String, Object> map = new HashMap<>();
//        map.put("sname", sname);
//        map.put("telephone", telephone);
        List<Result> lists = ResultService.RESULT_SERVICE.search(pageNo, pageSize, map);
        //总条数
        double pageTotal = ResultService.RESULT_SERVICE.findTotal();
        //总页数
        int pageNum = (int) Math.ceil(pageTotal / pageSize);

        //定义一个map对象存放json数据
        Map<String, Object> stuPage = new HashMap<>();
        stuPage.put("pageNo", pageNo);
        stuPage.put("pageSize", pageSize);
        stuPage.put("pageTotal", (int) pageTotal);
        stuPage.put("pageNum", pageNum);
//        stuPage.put("sname", sname);
//        stuPage.put("telephone", telephone);
        stuPage.put("exDatas", lists);
        String stuPageJSON = JSON.toJSONString(stuPage,SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNullNumberAsZero);

        System.out.println(stuPageJSON);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(stuPageJSON);

    }

    //增加成绩信息
    protected void exAddServlet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String examDate = request.getParameter("examDate");
        int stID =0;
        int sbID=0;
        float score=0f;

        try{
            stID = new Integer(request.getParameter("stuID"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            sbID = new Integer(request.getParameter("subID"));
        } catch (Exception e) {
            e.printStackTrace();
        }try{
            score  =new Float(request.getParameter("score"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(score<0||score>100){
            response.getWriter().print(false);
            return;
        }
        Result exResult = new Result(examDate, score, stID, sbID);
        System.err.println("exResult:"+exResult);
        int result = 0;
        try {
            result = ResultService.RESULT_SERVICE.add(exResult);
        } catch (Exception e) {
        }
        response.getWriter().print(result > 0 ? true : false);
    }

    //检查学生姓名并显示
    protected void checkStuName(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int stuID = Integer.parseInt(request.getParameter("stuID"));
        StudentService studentService= SpringMButil.getBean(StudentService.class);
        Student student=studentService.get(stuID);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String re="";
        if (student==null){
            re="没有该学生！";
        }else {
            re=student.getSname();
        }
        out.print(re);
        System.out.println(re);
        out.flush();
        out.close();
    }

    //检查课程姓名并显示
    protected void checkSubName(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int subID = Integer.parseInt(request.getParameter("subID"));
        Subject subject= SubjectService.SUBJECT_SERVICE.get(subID);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String re="";
        if (subject==null){
            re="没有该科目！";
        }else {
            re=subject.getSubjectname();
        }
        out.print(re);
        System.out.println(re);
        out.flush();
        out.close();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getServletPath();
        String action = path.substring(1, path.length() - 3);
        try {
            if (action.equals("doGet") || action.equals("doPost") || action.equals("service")) {
                response.sendError(500, "非法请求");
                return;
            }
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class,
                    HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            response.getWriter().print("error=>" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
